#ifndef ZYF_STACK_H
#define ZYF_STACK_H

#include<stdio.h>
#include<malloc.h>
#define STACK_SIZE 100 /*栈的初始大小*/
#define STACKINCREMENT 10 /*空间分配增量*/
#define ERROR 2
#define OK 1
typedef int ElemType;
typedef int Status;


typedef struct sqstack
{ 
	ElemType *bottom; /*栈不存在时值为NULL*/
	ElemType *top; //栈顶指针元素
	int stacksize; //当前已分空间,以元素为单位
}SqStack;


//初始化一个栈
Status Init_Stack(SqStack *S)
{
	S -> bottom = (ElemType *)malloc(STACK_SIZE*sizeof(ElemType));
	if (!S -> bottom)
		return ERROR;
	S -> top = S -> bottom;
	S -> stacksize = STACK_SIZE;

	return OK;
}



//压栈
Status push(SqStack *S,ElemType e)
{
	//int i = e;
	//top指向最上面元素的上一个空间
	if (S->top - S->bottom >= S->stacksize -1)
	{
		S->bottom = (ElemType *)realloc(S->bottom,(S->stacksize + STACKINCREMENT)*sizeof(ElemType));
		/*栈满追加存储空间*/
		if(!S->bottom)
			return ERROR;
		S->top = S->bottom+S->stacksize; //新地址加上已经使用过的空间
		S->stacksize+=STACKINCREMENT;
	}

	*S->top  = e;
	//printf("%d\n",*(S->top));
	//printf("%d\n",*S->bottom);
	S->top++;//top指向栈顶元素的上一个，先插入，top指针在上移
	return OK;
}

//弹栈
Status pop(SqStack *S,ElemType *e)
{//弹出栈顶元素
	if (S->top == S->bottom)
	{
		return ERROR;
	}

	S->top--;//先下移在弹出
	//printf("%d\n",*(S->top));
	*e = *S->top;

	return OK;
}

Status EmptyStack(SqStack *S)
{
	if (S -> top == S -> bottom)
		return OK;
	else
		return ERROR;
}

Status OverflowStack(SqStack *S)
{
	if (S -> top  - S -> bottom == STACK_SIZE - 1 )
		return OK;
	else
		return ERROR;
}

#endif